package com.yanglei.demo.framework.core.util;

import com.yanglei.demo.framework.LoginUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Collections;

/**
 * 安全服务工具类
 */
public class SecurityUtils {

    public static final String AUTHORIZATION_BEARER = "Bearer";

    private SecurityUtils() {
    }

    /**
     * 从请求中，获取认证 Token
     *
     * @param request 请求
     * @param header  认证Token对应的Header名字
     * @return 认证token
     */

    public static String obtainAuthorization(HttpServletRequest request, String header) {
        String authorization = request.getHeader(header);
        // 判断是不是字符串
        if (!StringUtils.hasText(authorization)) {
            return null;
        }
        // 获取得到token前缀的位置
        int index = authorization.indexOf(AUTHORIZATION_BEARER + " ");
        if (index == -1) {
            return null;
        }
        return authorization.substring(index + 7).trim();
    }

    /**
     * 设置当前用户
     *
     * @param loginUser
     * @param request
     */
    public static void setLoginUser(LoginUser loginUser, HttpServletRequest request) {
        // 创建Authentication，并设置上下文
        Authentication authentication = buildAuthentication(loginUser, request);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    private static Authentication buildAuthentication(LoginUser loginUser, HttpServletRequest request) {
        // TODO:不清楚这里是在设置什么东西
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, Collections.emptyList());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        return authenticationToken;
    }

    public static LoginUser getLoginUser() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        if (securityContext != null) {
            Authentication authentication = securityContext.getAuthentication();
            return authentication.getPrincipal() instanceof LoginUser ? (LoginUser) authentication.getPrincipal() : null;
        }
        return null;
    }
}
